package com.wfcm.controller;

import com.wfcm.annotation.IgnoreToken;
import com.wfcm.entity.Page;
import com.wfcm.entity.WfCollageActivityEntity;
import com.wfcm.entity.WfCollageOrderEntity;
import com.wfcm.service.WfCollageActivityService;
import com.wfcm.service.WfCollageOrderService;
import com.wfcm.service.WfGoodsOrderService;
import com.wfcm.utils.ISsoLoginHelper;
import com.wfcm.utils.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/groupbuy")
public class GroupBuyController {

    private static Logger logger = LoggerFactory.getLogger(GroupBuyController.class);

    @Autowired
    private WfGoodsOrderService goodsOrderService;

    @Autowired
    private WfCollageOrderService collageOrderService;

    @Autowired
    private WfCollageActivityService collageActivityService;

    /**
     * （新用户 or 老用户）已参团有效 status = 1 结果页面
     * 新用户（已参团无效 or 未参团）有邀请人有效 status = 2 邀请人团信息 参团按钮
     * 新用户（已参团无效 or 未参团）有邀请人无效 status = 3 提示邀请人团失效 开团按钮
     * 新用户（已参团无效 or 未参团）无邀请人 status = 4 开团按钮
     * 老用户（已参团无效 or 未参团）status = 5 开团按钮
     * 未登录用户 有邀请人有效 status = 6 邀请人团信息 参团按钮
     * 未登录用户 有邀请人无效 status = 7 提示邀请人团失效 开团按钮
     * 未登录用户 无邀请人 status = 8 开团按钮
     *
     * @param req
     * @param collageOrder
     * @return r
     */
    @IgnoreToken
    @RequestMapping("/main")
    public R main(HttpServletRequest req, @RequestBody WfCollageOrderEntity collageOrder) {
        R r = R.ok();
        try {
            WfCollageActivityEntity activity = collageActivityService.queryObject(collageOrder.getActivityId());
            r.put("activityInfo", activity);
            if (activity.getActivityType().equals(2)) {
                r.put("randomList", collageOrderService.queryRandomGroupBuyList(collageOrder.getActivityId(), 0, 3));
            }
            Integer userId = ISsoLoginHelper.confirm(req);
            if (null != userId) {
                // 已登陆
                WfCollageOrderEntity groupBuyOrder = collageOrderService.queryGroupBuying(userId, collageOrder.getActivityId(), null);
                if (null != groupBuyOrder) {
                    String userAgent = req.getHeader("user-agent");
                    if (userAgent.contains("okhttp")) {
                        activity.setEndtime(collageOrderService.queryGroupBuyList(groupBuyOrder.getCollageorder()).get(0).getEndtime());
                        r.put("activityInfo", activity);
                    }
                    // 已参团 - 有效
                    r.put("status", 1);
                    r.put("groupBuyStatus", groupBuyOrder.getStatus());
                    r.put("results", collageOrderService.queryGroupBuyList(groupBuyOrder.getCollageorder()));
                } else {
                    if (activity.getActivityType().equals(1)) {
                        // 新人参团
                        // 已参团无效 or 无参团
                        if (goodsOrderService.queryAlreadyPayByUserId(userId) == 0) {
                            // 新用户
                            if (null != collageOrder.getInviterId()) {
                                // 有邀请人
                                WfCollageOrderEntity inviterGroupBuyOrder = collageOrderService.
                                        queryGroupBuying(collageOrder.getInviterId(), collageOrder.getActivityId(), 2);
                                if (null != inviterGroupBuyOrder) {
                                    // 邀请人有效
                                    r.put("status", 2);
                                    r.put("type", 1);
                                    r.put("userId", collageOrder.getInviterId());
                                    r.put("results", collageOrderService.queryGroupBuyList(inviterGroupBuyOrder.getCollageorder()));
                                } else {
                                    r.put("status", 3);
                                    r.put("type", 2);
                                    r.put("userId", userId);
                                }
                            } else {
                                // 无邀请人
                                r.put("status", 4);
                                r.put("type", 2);
                                r.put("userId", userId);
                            }
                        } else {
                            // 老用户
                            r.put("status", 5);
                            r.put("type", 2);
                            r.put("userId", userId);
                        }
                    } else {
                        // 都可参团
                        if (null != collageOrder.getInviterId()) {
                            // 有邀请人
                            WfCollageOrderEntity inviterGroupBuyOrder = collageOrderService.
                                    queryGroupBuying(collageOrder.getInviterId(), collageOrder.getActivityId(), 2);
                            if (null != inviterGroupBuyOrder) {
                                // 邀请人有效
                                r.put("status", 2);
                                r.put("type", 1);
                                r.put("userId", collageOrder.getInviterId());
                                r.put("results", collageOrderService.queryGroupBuyList(inviterGroupBuyOrder.getCollageorder()));
                            } else {
                                // 邀请人无效
                                r.put("status", 3);
                                r.put("type", 2);
                                r.put("userId", userId);
                            }
                        } else {
                            // 无邀请人
                            r.put("status", 4);
                            r.put("type", 2);
                            r.put("userId", userId);
                        }
                    }
                }
            } else {
                // 未登录
                if (null != collageOrder.getInviterId()) {
                    // 有邀请人
                    WfCollageOrderEntity inviterGroupBuyOrder = collageOrderService.
                            queryGroupBuying(collageOrder.getInviterId(), collageOrder.getActivityId(), 2);
                    if (null != inviterGroupBuyOrder) {
                        // 邀请人有效
                        r.put("status", 6);
                        r.put("type", 1);
                        r.put("userId", collageOrder.getInviterId());
                        r.put("results", collageOrderService.queryGroupBuyList(inviterGroupBuyOrder.getCollageorder()));
                    } else {
                        r.put("status", 7);
                        r.put("type", 2);
                    }
                } else {
                    // 无邀请人
                    r.put("status", 8);
                    r.put("type", 2);
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return r;
    }

    @IgnoreToken
    @RequestMapping("activityList")
    public R activityList(HttpServletRequest req) {
        R r = R.ok();
        try {
            r.put("results", collageActivityService.queryAllActivity(req.getHeader("version")));
        } catch (Exception e) {
            r = R.error();
            logger.error(e.getMessage(), e);
        }
        return r;
    }

    @RequestMapping("record")
    public R record(HttpServletRequest req, @RequestBody Page page) {
        R r = R.ok();
        try {
            Integer userId = ISsoLoginHelper.confirm(req);
            int recordTotal = collageOrderService.recordTotal(userId);
            if (recordTotal > 0) {
                page.setTotalRow(recordTotal);
            }
            List<WfCollageOrderEntity> recordList = collageOrderService.record(userId, page.getStart(), page.getPageSize());
            r.put("results", recordList);
            r.put("page", page);
        } catch (Exception e) {
            r = R.error();
            logger.error(e.getMessage(), e);
        }
        return r;
    }

    @IgnoreToken
    @RequestMapping("random")
    public R passer(@RequestBody WfCollageOrderEntity order) {
        R r = R.ok();
        Page page = new Page();
        try {
            page.setCurPage(order.getCurPage());
            int ramdomTotal = collageOrderService.queryRandomGroupBuyTotal(order.getActivityId());
            if (ramdomTotal > 0) {
                page.setTotalRow(ramdomTotal);
            }
            List<WfCollageOrderEntity> randomList = collageOrderService.queryRandomGroupBuyList(order.getActivityId(), page.getStart(), page.getPageSize());
            r.put("results", randomList);
            r.put("page", page);
        } catch (Exception e) {
            r = R.error();
            logger.error(e.getMessage(), e);
        }
        return r;
    }
}
